package com.healMyself.dao.impl;

import com.healMyself.dao.RecordDao;
import com.healMyself.pojo.Record;
import com.healMyself.util.C3p0Conn;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

public class RecordDaoImpl implements RecordDao {
    private QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
    @Override
    public int addRecord(Record record) {
        String sql = "insert into record values(null,?,?,?,?,?,?) ";
        try {
            return qr.update(C3p0Conn.getConn(), sql,
                    record.getUserId(), record.getMedicine(), record.getDosage(), record.getTheTime(), record.getFeelings(), record.getPlace());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Record> queryRecord(int userId, String medicine, Timestamp statTime, Timestamp Deadline, String place) {
        String sql = "";
        StringBuilder sb = new StringBuilder("SELECT * FROM record where userId='" + userId + "'" );
        if (medicine != null && !"".equals(medicine)){
            sb.append(" AND medicine LIKE '%" + medicine + "%'" );
        }
        if (place != null && !"".equals(place)){
            sb.append(" AND place LIKE '%" + place + "%'");
        }
        if (statTime != null && !"".equals(statTime) && Deadline != null && !"".equals(Deadline)){
            sb.append(" AND theTime>" + statTime + " AND theTime <" +Deadline);
        }
        sql = sb.toString();
        List<Record> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<>(Record.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        System.out.println(list);
        return list;
    }
}
